<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @open="openDialog">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="auto" label-position="top" class="menu-dialog">
      <el-form-item label="角色名称:" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="角色描述:" prop="description">
        <el-input v-model="form.description" autosize type="textarea" />
      </el-form-item>
      <el-form-item>
        <div class="from-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!-- <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确认</el-button>
      </span>
    </template> -->
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, getCurrentInstance, toRef } from 'vue'
import { ElMessage } from 'element-plus'
import { internetApi } from '@/api/api.js'

const currentInstance = getCurrentInstance()
const { $request } = currentInstance.appContext.config.globalProperties

const ruleFormRef = ref()
const dialogVisible = ref(false)
const dialogTitle = ref('') //弹窗标题
const form = reactive({
  id: '',
  name: '',
  description: ''
})
const props = defineProps({
  getMenuList: {
    type: Function,
    default: () => {}
  }
})
const rules = reactive({
  name: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
    { min: 2, max: 8, message: '2-8个字之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '角色描述不能为空', trigger: 'blur' },
    { max: 100, message: '不超过100个字', trigger: 'blur' }
  ]
})
// 打开弹窗，父组件调用的方法，且弹窗方法
const openDialog = (row, type) => {
  if (type == 'add') {
    dialogTitle.value = '新建角色'
    form.id = null
    form.name = null
    form.description = null
  } else if (type == 'edit') {
    dialogTitle.value = '编辑角色'
    form.id = row.id
    form.name = row.name
    form.description = row.description
  }
  dialogVisible.value = true
  console.log('row', row)
  // console.log('type',type)
}

// 确认添加菜单
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (form.id) {
        $request(internetApi.updateRole, form)
      } else {
        $request(internetApi.addRole, form)
      }
      dialogVisible.value = false
      // setTimeout(()=>{
      console.log('2------------------------------------>', props.getMenuList())
      props.getMenuList()
      // },50)
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 导出，使父组件可调用子组件的方法或者值
defineExpose({
  openDialog
})
</script>
<style lang="scss" scoped>
.from-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.menu-dialog {
  .el-select {
    width: 100%;
  }
}
</style>
